﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ZhongJia.Lock.Infrastructure.Extensions
{
    public static class CollectionExtensions
    {
        public static bool IsNullOrEmpty<T>(this ICollection<T> source)
        {
            return source == null || source.Count <= 0;
        }

        public static bool AddIfNotContains<T>(this ICollection<T> source, T item)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (source.Contains(item))
            {
                return false;
            }

            source.Add(item);
            return true;
        }

        public static void RemoveWhere<T>(this ICollection<T> collection, Predicate<T> predicate)
        {
            if (collection == null)
                throw new ArgumentNullException("collection");

            var deleteList = collection.Where(child => predicate(child)).ToList();
            deleteList.ForEach(t => collection.Remove(t));
        }

        public static ICollection<T> ReduceTimeSeries<T>(this ICollection<T> items, Func<T, DateTime> dateSelector, Func<ICollection<T>, DateTime, T> reducer, int dataPoints)
        {
            if (items.Count <= dataPoints)
                return items;

            var minTicks = items.Min(dateSelector).Ticks;
            var maxTicks = items.Max(dateSelector).Ticks;

            var bucketSize = (maxTicks - minTicks) / dataPoints;
            var buckets = new List<long>();
            long currentTick = minTicks;
            while (currentTick < maxTicks)
            {
                buckets.Add(currentTick);
                currentTick += bucketSize;
            }

            buckets.Reverse();

            return items.GroupBy(i => buckets.First(b => dateSelector(i).Ticks >= b)).Select(g => reducer(g.ToList(), new DateTime(g.Key))).ToList();
        }
    }
}
